﻿@model Amazon.Checkout.ViewModels.ShippingNewUpdateViewModel
           
@using System.Text.RegularExpressions;
@using System.Web.Mvc;
@using Amazon.Checkout.Helpers;

@{ Script.Require("JQuery").AtHead(); }

<h1>@T((Model.ShippingId == null || Model.ShippingId == 0) ? "New Shipping Method" : "Edit Shipping Method")</h1>

@using (Html.BeginFormAntiForgeryPost())
{
    var serviceLevels = new SelectList(AmazonCheckout.AvailableServiceLevels, "Key", "Value", string.Empty);
    
    if (Model.ShippingId != null || Model.ShippingId == 0)
    {
        @Html.HiddenFor(m => m.ShippingId)
    }
                          
    @Html.ValidationSummary()
    
    <fieldset>
        @Html.LabelFor(m => m.DisplayableShippingLabel, T("Displayable Shipping Label:")) 
        @Html.TextBoxFor(m => m.DisplayableShippingLabel, new { @class = "text" })
        
        @GetRegionTable(@Model.IncludedRegions, @Model.IncludedRegionsString, true)
        @GetRegionTable(@Model.ExcludedRegions, @Model.ExcludedRegionsString, false)
                
        <h3>Shipping Information</h3>

        <div id="shipment-type-selector">
            <div style="@GetShipmentTypeVisibility("shipment")" class="shipment">Rate: @Html.TextBoxFor(m => m.ShipmentBasedShippingRate, new { @class = "text" })</div>
            <div style="@GetShipmentTypeVisibility("weight")" class="weight">Rate: @Html.TextBoxFor(m => m.WeightBasedShippingRate, new { @class = "text" })</div>
            <div style="@GetShipmentTypeVisibility("item")" class="item">Rate: @Html.TextBoxFor(m => m.ItemQuantityBasedShippingRate, new { @class = "text" })</div>
        </div>

        @Html.RadioButton("ShipmentRateType", "shipment", IsRadioSelected("shipment"), new { @class = "shipment" }) <span style="vertical-align:top;">Shipment Based Shipping Rate</span>
        @Html.RadioButton("ShipmentRateType", "weight", IsRadioSelected("weight"), new { @class = "weight" })<span style="vertical-align:top;">Weight Based Shipping Rate</span>
        @Html.RadioButton("ShipmentRateType", "item", IsRadioSelected("item"), new { @class = "item" })<span style="vertical-align:top;">Item Quantity Based Shipping Rate</span>

       <div>
            @Html.LabelFor(m => m.ServiceLevel, T("Service Level")) 
            @Html.DropDownListFor(m => m.ServiceLevel, serviceLevels)
        </div>
    </fieldset>

    <fieldset class="with-checkbox">
        <span>
            @Html.CheckBox("PoBoxSupported")
            <label for="PoBoxSupported" class="forcheckbox">@T("Is PO Box Supported")</label>
        </span>        
    </fieldset>
    
    <fieldset>
        <button class="primaryAction" type="submit">@T((Model.ShippingId == null || Model.ShippingId == 0) ? "Save" : "Update")</button>
    </fieldset>
}
@functions {
    string GetShipmentTypeVisibility(string shipmentType) {
        if (string.IsNullOrEmpty(Model.ShipmentRateType) && shipmentType == "shipment")
            return "display:block;";
        
        if ((Model.ShipmentRateType ?? "") == shipmentType) 
            return "display:block;";

        return "display:none;";
    }

    bool IsRadioSelected(string shipmentType)
    {
        if (string.IsNullOrEmpty(Model.ShipmentRateType) && shipmentType == "shipment")
            return true;

        if ((Model.ShipmentRateType ?? "") == shipmentType)
            return true;

        return false;
    }
}  

@helper GetRegionTable(IEnumerable<AmazonCheckout.Region> regions, string regionsString, bool includedMode)
{   
    var mode = (includedMode ? "included" : "excluded");
    var regionTypeEnum = Enum.GetNames(typeof(AmazonCheckout.AmazonRegionTypes)).ToList();
    var regionTypes = new SelectList(regionTypeEnum.ToDictionary(k => k, v => Regex.Replace(v, "([A-Z])([a-z])", " $1$2")), "Key", "Value", string.Empty);
    var usStates = new SelectList(AmazonCheckout.AvailableUSStates, "Key", "Value", string.Empty);
    var predefinedRegions = new SelectList(AmazonCheckout.AvailablePredefinedRegions, "Key", "Value", string.Empty);
    var countries = new SelectList(AmazonCheckout.AvailableCountries, "Key", "Value", string.Empty);
    
    <h3>@(includedMode ? "Included" : "Excluded") Regions</h3>
    <table class="items regions @mode" summary="@T("List of " + (includedMode ? "Included" : "Excluded") + " regions.")">
        <colgroup>
            <col id="Col1" width="200"/>
            <col id="Col2" />
            <col id="Col3" width="200"/>
        </colgroup>
        <thead>
            <tr>
                <th scope="col">@T("RegionType")</th>
                <th scope="col">@T("Region")</th>
                <th scope="col">@T("Actions")</th>
            </tr>
        </thead>
        <tr>
            <td>
                @Html.DropDownList(mode + "-region-type-select", regionTypes, new { @class = "region-type " + mode })
            </td>
            <td>
                @Html.DropDownList(mode + "-usstate-select", usStates)
                @Html.DropDownList(mode + "-country-select", countries, new { style = "display:none;" })
                @Html.DropDownList(mode + "-predefined-select", predefinedRegions, new { style = "display:none;" })
                @Html.TextBox(mode + "-zipregion", "", new { style = "display:none;", @class = "text" })
                @Html.TextBox(mode + "-postalregion", "", new { style = "display:none;", @class = "text" })
            </td>
            <td><button class="primaryAction add-region @mode" type="button" name="add-region">@T("Add Region")</button></td>
        </tr>
        @if (regions != null && regions.Any())
        {
            foreach (var item in regions)
            {
            <tr>
                <td>@item.FriendlyName</td>
                <td>@item.GetDisplayValue()</td>
                <td><a style="cursor:pointer" class="delete-region @mode" rel="@item.GetType().Name|@item.GetValue()">@T("Delete")</a></td>
            </tr>
            }
        }
    </table>
        
    <input id="@(includedMode ? "IncludedRegionsString" : "ExcludedRegionsString")" 
            name="@(includedMode ? "IncludedRegionsString" : "ExcludedRegionsString")" 
            value="@regionsString" 
            type="hidden" />
}

<script type="text/javascript">
    $(document).ready(function () {

        $("input[type='radio']").change(function () {
            $("#shipment-type-selector div").hide();
            $("#shipment-type-selector div." + $(this).attr('class')).show();
        });

        $("button.add-region").click(function () {
            var mode = $(this).hasClass('included') ? 'included' : 'excluded';

            var regionType = $('#' + mode + '-region-type-select');
            var usState = $('#' + mode + '-usstate-select');
            var countries = $('#' + mode + '-country-select');
            var prefefinedRegions = $('#' + mode + '-predefined-select');
            var zipRegion = $('#' + mode + '-zipregion');
            var postalRegion = $('#' + mode + '-postalregion');

            var regionsString = (mode == "included") ? $("#IncludedRegionsString") : $("#ExcludedRegionsString");

            var selectedRegionTypeValue = $("option:selected", regionType).val();
            var selectedRegionTypeText = $("option:selected", regionType).text();

            var selectedValue = "";
            var selectedText = "";

            switch (regionType.val()) {
                case "USStateRegion":
                    selectedValue = $("option:selected", usState).val();
                    selectedText = $("option:selected", usState).text();
                    break;
                case "USZipRegion":
                    selectedValue = zipRegion.val();
                    selectedText = zipRegion.val();
                    break;
                case "PredefinedRegion":
                    selectedValue = $("option:selected", prefefinedRegions).val();
                    selectedText = $("option:selected", prefefinedRegions).text();
                    break;
                case "CountryRegion":
                    selectedValue = $("option:selected", countries).val();
                    selectedText = $("option:selected", countries).text();
                    break;
                case "PostalRegion":
                    selectedValue = postalRegion.val();
                    selectedText = postalRegion.val();
                    break;
            }

            var item = (selectedRegionTypeValue + "|" + selectedValue);

            if (regionsString.val().indexOf(item) >= 0)
                return;

            var row = $('<tr>').append($('<td>').text(selectedRegionTypeText))
                                .append($('<td>').text(selectedText))
                                .append($('<td>').append('<a style="cursor:pointer" class="delete-region" rel="' + item + '">Delete</a>'));

            $(this).closest("table").append(row);
            var value = (regionsString.val() + "," + item).sanetizeJoinValues();
            regionsString.val(value);

        });

        $("select.region-type").change(function () {
            var mode = $(this).hasClass('included') ? 'included' : 'excluded';
            var selectedRegionType = $(this).val();

            var usState = $('#' + mode + '-usstate-select').hide();
            var countries = $('#' + mode + '-country-select').hide();
            var prefefinedRegions = $('#' + mode + '-predefined-select').hide();
            var zipRegion = $('#' + mode + '-zipregion').hide();
            var postalRegion = $('#' + mode + '-postalregion').hide();

            switch (selectedRegionType) {
                case "USStateRegion":
                    usState.show();
                    break;
                case "USZipRegion":
                    zipRegion.show();
                    break;
                case "PredefinedRegion":
                    prefefinedRegions.show();
                    break;
                case "CountryRegion":
                    countries.show();
                    break;
                case "PostalRegion":
                    postalRegion.show();
                    break;
            }
        });

        $("a.delete-region").live('click', function () {
            var regionsString = $(this).hasClass('included') ? $("#IncludedRegionsString") : $("#ExcludedRegionsString");

            var value = regionsString.val()
                                     .replace($(this).attr('rel'), '')
                                     .sanetizeJoinValues();
            regionsString.val(value);
            $(this).closest('tr').remove();
        });

        String.prototype.sanetizeJoinValues = function () {
            return $.trim(this.replace(/,,/, ',').replace(/,$/, '').replace(/^,/, ''));
        }
    });    
</script>